package com.goodfox.web.generic.file.controller;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.goodfox.web.generic.file.service.FileDownloadService;


/**
 * 文件下载Controller类，文件下载的action请求链接
 * @author qin gt
 *
 */
@Controller
@RequestMapping("/fileDownload")
public class FileDownloadController {

	/** log4j日志器 */
	private Logger logger=Logger.getLogger(FileDownloadController.class);
	
	/** 文件查询Service */
	@Autowired
	private FileDownloadService fileDownloadService;
	
	@RequestMapping(value="downloadPath.shtml")
	public void downloadPath(HttpServletRequest request,HttpServletResponse response){
		logger.info("执行文件下载");
		String webPath = request.getSession().getServletContext().getRealPath("WEB-INF").replace("\\", "/")+"/";
		String filePath = request.getParameter("path");
		byte[] bytes=fileDownloadService.getPathBytes(webPath,filePath);
		try{
			OutputStream out = response.getOutputStream();
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/octet-stream");
			String name = request.getParameter("name").trim();
			response.setHeader("Content-disposition","attachment;filename="+name);
			for(byte b:bytes){
				out.write(b);
			}
			out.flush();
		}catch(Exception ex){
			ex.printStackTrace();
			logger.error("文件下载失败",ex);
		}
	}
	
}
